package com.koudai.reader.vo;

import java.util.UUID;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.telephony.cdma.CdmaCellLocation;
import android.telephony.gsm.GsmCellLocation;
import android.util.DisplayMetrics;
import android.view.WindowManager;

public class EndUser {

    private String uid;
    private int gold;
    private int bookCount;
    private boolean isVip;
    private int version;
    
    public int getVersion() {
        return version;
    }

    public void setVersion(int version) {
        this.version = version;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public int getGold() {
        return gold;
    }

    public String getGlodStr() {
        return String.valueOf(gold);
    }
    
    public void setGold(int gold) {
        this.gold = gold;
    }

    public int getBookCount() {
        return bookCount;
    }

    public void setBookCount(int bookCount) {
        this.bookCount = bookCount;
    }

    public void updateGold(int jifen) {
        this.gold += jifen;
    }
    
    // =====================================
    public double density;
    private String deviceid;
    private String macAddress;
    private String phoneType;
    
    /** 设备ID */
    public String sesstionid;
    
    public String keyDev = new String("000000000000000");

    public int retry_times = 0;

    /** 系统型号(比如MB525) */
    public String typeDev = new String("simulation");

    /** 操作系统(例如:Android 2.3.7) */
    public String osVer = new String("2.1-update1");

    /** 分辨率(例如:480*854) */
    public String resolution = new String("320*480");

    /** 网络编号46000，46002编号(134/159号段):中国移动 46001:中国联通 46003:中国电信 */
    public String simOper = "";

    /** 移动通信类型 (无信号,GSM信号,CDMA信号 ) */
    public String phonetype = new String("NONE");

    /** 设备的软件版本号 */
    public String deviceSoftwareVer = "";

    /** 国家代码 */
    public String countrycode = "";

    /** 经纬度 */
    public String lat_Long = "";

    /** 方向 */
    public String orientation = "";

    /** 网络(2G/3G,wifi) */
    public String netType = new String("2G/3G");

    /** 地理位置 */
    public Location location;
    public String phoneNumber;
    public boolean networkEnable;
    public int wifi;
    public String channelid;
    public String appVesionCode;
    public String manufacturer;
    public int cid;
    public int lac;
    // BSSID，wifi 路由器mac地址,当前手机连接的WiFi热点的MAC地址
    public String bssid = "";

    /* */
    private boolean isInitilized;
    public int screenWidth;
    public int screenHeight;
    
    private static EndUser instance = new EndUser();

    private EndUser() {

    }

    public static EndUser getInstance() {

        return instance;
    }

    public void init(Context context) {
        
        isInitilized = true;
        
        try {
            version = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (NameNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        
        sesstionid = UUID.randomUUID().toString();
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        density = dm.density;
        // 屏幕密度（像素比例：0.75/1.0/1.5/2.0）  
        int densityDPI = dm.densityDpi;     // 屏幕密度（每寸像素：120/160/240/320）  
        float xdpi = dm.xdpi;             
        float ydpi = dm.ydpi;  
          
        screenWidth  = dm.widthPixels;      // 屏幕宽（像素，如：480px）  
        screenHeight = dm.heightPixels;     // 屏幕高（像素，如：800px）  
          
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (tm == null) {
            return;
        }
        deviceid = tm.getDeviceId();
        WifiManager wifi_service = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiinfo = wifi_service.getConnectionInfo();
        // 
        if (wifiinfo.getBSSID() != null) {
            bssid = wifiinfo.getBSSID();
        }
        // 
        if (wifiinfo.getMacAddress() != null) {
            macAddress = wifiinfo.getMacAddress();
        }

        try {
            if (context == null) {
                return;
            }
            // 
            lat_Long = getLat_Long(context);
            if (lat_Long != null) {
                // do nothing
            } else {
                lat_Long = "";
            }
            // 0:PORTRAIT|1:LANDSCAPE
            orientation = context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT ? "0" : "1";

            // 
            phoneNumber = tm.getLine1Number();
            if (phoneNumber == null) {
                phoneNumber = "";
            }

            String devid = tm.getDeviceId();
            if ((devid != null) && (devid.length() > 0)) {
                keyDev = new String(devid);
            }
            typeDev = new String(Build.MODEL);
            typeDev = typeDev.replaceAll(" ", "");
            osVer = new String(Build.VERSION.RELEASE);
            osVer = osVer.replaceAll(" ", "");

            WindowManager WM = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            int screenWidth = WM.getDefaultDisplay().getWidth();
            int screenHeight = WM.getDefaultDisplay().getHeight();

            resolution = new String(Integer.toString(screenWidth) + "*" + Integer.toString(screenHeight));

            if (tm.getSimState() == 5) {

                simOper = tm.getSimOperator();
            }

            if (tm.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) {
                phonetype = "GSM";
            } else if (tm.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
                phonetype = "CDMA";
            } else {
                phonetype = "NONE";
            }

            deviceSoftwareVer = tm.getDeviceSoftwareVersion();
            if (deviceSoftwareVer == null) {
                deviceSoftwareVer = "";
            }

            countrycode = tm.getNetworkCountryIso().toLowerCase();

            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo ni = cm.getActiveNetworkInfo();
            if (ni != null) {

                if (ni.isConnected()) {
                    networkEnable = true;
                }

                netType = ni.getTypeName();

                if ("WIFI".equalsIgnoreCase(netType)) {
                    this.wifi = 1;
                }
            } else {
                netType = new String("");
            }

            this.channelid = getSDKChannel(context);

            String appPackageName = context.getPackageName();
            try {
                int vCode = context.getPackageManager().getPackageInfo(appPackageName, 0).versionCode;
                appVesionCode = String.valueOf(vCode);

            } catch (NameNotFoundException e) {
            }

            manufacturer = Build.MANUFACTURER.toLowerCase();

            int type = tm.getNetworkType();
            if (type == TelephonyManager.PHONE_TYPE_GSM // GSM
                    || type == TelephonyManager.NETWORK_TYPE_EDGE || type == TelephonyManager.NETWORK_TYPE_HSDPA) {

                GsmCellLocation gsm = ((GsmCellLocation) tm.getCellLocation());
                if (gsm != null) {

                    simOper = tm.getSimOperator();

                    cid = gsm.getCid();

                    lac = gsm.getLac();
                } else {
                    
                }
            } else if (type == TelephonyManager.NETWORK_TYPE_CDMA // ����cdma��
                    || type == TelephonyManager.NETWORK_TYPE_1xRTT
                    || type == TelephonyManager.NETWORK_TYPE_EVDO_0
                    || type == TelephonyManager.NETWORK_TYPE_EVDO_A) {

                CdmaCellLocation cdma = (CdmaCellLocation) tm.getCellLocation();
                if (cdma != null) {
             
                    String mcc = tm.getNetworkOperator().substring(0, 3);
                  
                    String mnc = String.valueOf(cdma.getSystemId());
                    simOper = mcc + mnc;
                  
                    cid = cdma.getBaseStationId();
                
                    lac = cdma.getNetworkId();
                } else {
                    
                }
            }

        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    /**
     * @return the isInitilized
     */
    public boolean isInitilized() {
        return isInitilized;
    }

    /**
     * @param isInitilized the isInitilized to set
     */
    public void setInitilized(boolean isInitilized) {
        this.isInitilized = isInitilized;
    }

    /**
     * @return the deviceid
     */
    public String getDeviceid() {
        return deviceid == null ? "" : deviceid;
    }

    /**
     * @param deviceid
     *            the deviceid to set
     */
    public void setDeviceid(String deviceid) {
        this.deviceid = deviceid;
    }

    /**
     * @return the macAddress
     */
    public String getMacAddress() {
        return macAddress == null ? "" : macAddress;
    }

    /**
     * @param macAddress
     *            the macAddress to set
     */
    public void setMacAddress(String macAddress) {
        this.macAddress = macAddress;
    }

    /**
     * @return the phoneType
     */
    public String getPhoneType() {
        return phoneType;
    }

    /**
     * @param phoneType
     *            the phoneType to set
     */
    public void setPhoneType(String phoneType) {
        this.phoneType = phoneType;
    }

    /**

     */
    public String getLat_Long(Context context) {
        String locationString = null;
        try {
            String serviceName = "location";

            // A LocationManager for controlling location (e.g., GPS) updates.
            LocationManager locationManager = (LocationManager) context.getSystemService(serviceName);
            Criteria criteria = new Criteria();
            // 
            criteria.setAccuracy(1);
            criteria.setAltitudeRequired(false);
            criteria.setBearingRequired(false);
            criteria.setCostAllowed(true);
            // 
            criteria.setPowerRequirement(1);

            // name of the provider that best matches the requirements
            String provider = locationManager.getBestProvider(criteria, true);
            // Location location = null;

            if ((provider != null) && (provider.length() > 0)) {

                location = locationManager.getLastKnownLocation(provider);
            }

            if (location != null) {


                double lat = location.getLatitude();

                double lng = location.getLongitude();
                locationString = lat + "," + lng;
                
            } else {
                
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return locationString;
    }

    /**
     * <pre>
     * 
     * </pre>
     * 
     * @param paramContext
     * @return
     */
    private static String getSDKChannel(Context paramContext) {
        Object localObject1 = "Unknown";
        try {
            PackageManager localPackageManager = paramContext.getPackageManager();
            ApplicationInfo localApplicationInfo = localPackageManager.getApplicationInfo(paramContext.getPackageName(), 
                    PackageManager.GET_META_DATA);
            if ((localApplicationInfo != null) && (localApplicationInfo.metaData != null)) {
                Object localObject2 = localApplicationInfo.metaData.get("ZHUAMOB_OFFER_SDK_CHANNELID");
                if (localObject2 != null) {
                    String str = localObject2.toString();
                    if (str != null) {
                        localObject1 = str;

                    } else {
                        
                    }
                }
            }
        } catch (Throwable e) {

            e.printStackTrace();
        }
        return (String) localObject1;
    }

    public boolean isVip() {
        return isVip;
    }

    public void setVip(boolean isVip) {
        this.isVip = isVip;
    }
}
